package com.app.twth.net;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * =====================================
 * <p>
 * 描    述 : 生成json字符串对象
 * =====================================
 */
public class RequestBodyUtil {

    public static RequestBody getRequestBody(Map<String, Object> hashMap) {

//        return RequestBody.create(MediaType.parse("application/json; charset=UTF-8"), new JSONObject(hashMap).toString());
        return RequestBody.create(MediaType.parse("application/json; charset=UTF-8"), new Gson().toJson(hashMap));

    }

    public static RequestBody getRequestBody(HttpBean model) {

        return RequestBody.create(MediaType.parse("application/json; charset=UTF-8"), new Gson().toJson(model));

    }

    public static RequestBody getFormRequestBody(Map<String, Object> hashMap) {

        return RequestBody.create(MediaType.parse("multipart/form-data"), new JSONObject(hashMap).toString());

    }

    //zxf  https://blog.csdn.net/llp1990311/article/details/125540253
    public static RequestBody getFormUrlEncodedRequestBody(Map<String, Object> hashMap) {

        StringBuilder builder = new StringBuilder();

        //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
            String name = entry.getKey();
            Object value = entry.getValue();
            if (builder.length() != 0) {
                builder.append('&');
            }
            builder.append(name);
            if (value != null) {
                builder.append('=');
                builder.append(value);
            }
        }
        //}

        return RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"), builder.toString());

    }
}
